#include "Camera.h"

Camera::Camera(const Vector3F & position):_position(position), _cible()
{
	_phi = 0;
	_theta = 0;
	vectorsFromAngles();

	_posX = 320;
	_posY = 240;

	_vitesse = 0.01;
	_sensib = 0.2;
	_mvtVertA = false;
	
	_event["haut"] = SDLK_z;
	_event["bas"] = SDLK_s;
	_event["gauche"] = SDLK_q;
	_event["droite"] = SDLK_d;
	_event["boost"] = SDLK_SPACE;
	
	_action[_event["haut"]] = false;
	_action[_event["bas"]] = false;
	_action[_event["gauche"]] = false;
	_action[_event["droite"]] = false;
	_action[_event["boost"]] = false;

	SDL_WM_GrabInput(SDL_GRAB_ON);
	SDL_ShowCursor(SDL_DISABLE);

}

 void Camera::mvtSouris()
 {
	 int i,j;
	 SDL_GetMouseState(&i, &j);
	 _relX = i - _posX; _relY = j - _posY;
	 _posX = i; _posY = j;
	_theta -= _relX*_sensib;
	_phi -= _relY*_sensib;
	vectorsFromAngles();
 }
 
 void Camera::moletteSouris(const SDL_MouseButtonEvent & event)
 {
	 if ((event.button == SDL_BUTTON_WHEELUP)&&(event.type == SDL_MOUSEBUTTONDOWN)) //haut
	{
		_mvtVertA = true;
		_tpsMax = 250;
		_mvtVertDir = 1;

	}
	else if ((event.button == SDL_BUTTON_WHEELDOWN)&&(event.type == SDL_MOUSEBUTTONDOWN)) //bas
	{
		_mvtVertA = true;
		_tpsMax = 250;
		_mvtVertDir = -1;
	}

 }
 
 void Camera::clavier(Uint8* keystate)
 {
   _action[_event["haut"]] = keystate [_event["haut"]];
   _action[_event["bas"]] = keystate [_event["bas"]];
   _action[_event["gauche"]] = keystate [_event["gauche"]];
   _action[_event["droite"]] = keystate [_event["droite"]];
   _action[_event["boost"]] = keystate [_event["boost"]];
 }

 void Camera::animer( Uint32 tps)
 {
	float vitReel = (_action[_event["boost"]])?10*_vitesse:_vitesse;
	if (_action[_event["haut"]]) 
		_position += _avant * (vitReel * tps);
	if (_action[_event["bas"]])
		_position -= _avant * (vitReel * tps);
	if (_action[_event["gauche"]])
		_position += _gauche * (vitReel * tps);
	if (_action[_event["droite"]]) 
		_position -= _gauche * (vitReel * tps);
	if (_mvtVertA)
	{
	if (tps > _tpsMax)
		_mvtVertA = false;
	else
		_tpsMax -= tps;
	_position += Vector3F(0,0,_mvtVertDir*vitReel*tps);
	}
	_cible = _position + _avant;


 }
 
 void Camera::setVitesse(float vitesse)
 {
	 _vitesse = vitesse;
 }
 
 void Camera::setSensibilite(float sensib)
 {
	 _sensib = sensib;
 }

 void Camera::setPosition(const Vector3F & position)
 {
	 _position = position;
 }

 void Camera::look()
 {
	 gluLookAt(_position.X, _position.Y, _position.Z,
			   _cible.X, _cible.Y, _cible.Z,
		       0,        0,        1);
 }

 Camera::~Camera()
 {
	SDL_WM_GrabInput(SDL_GRAB_OFF);
    SDL_ShowCursor(SDL_ENABLE);

 }


void Camera::vectorsFromAngles()
{
	Vector3F up(0,0,1); 
	if (_phi > 89)
		_phi = 89;
	else if (_phi < -89)
		_phi = -89;

	float temp = cos(_phi*M_PI/70);
	_avant.Z = sin(_phi*M_PI/70);
	_avant.X = temp*cos(_theta*M_PI/70);
	_avant.Y = temp*sin(_theta*M_PI/70);

	_gauche = up.crossProduct(_avant);
	_gauche.normalize();


	_cible = _position + _avant;

}


Vector3F Camera::getCible()
{
	return _cible;
}
